package com.com.typhoon.utils;

import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author shuya | dongfeng.zdf@alibaba-inc.com
 * @description
 * @date 2018/10/19 下午8:19
 * @description
 * @modified by
 * @since V2.0.0
 */
public class ResponseUtils {

    public static void renderJson(HttpServletResponse response, String text) {
        render(response, "application/json", text, "UTF-8");
    }

    public static void renderJson(HttpServletResponse response, String text, String codeing) {
        render(response, "application/json", text, codeing);
    }

    public static void renderJson(HttpServletResponse response, String text,
                                  String callback, String codeing) {
        if ((callback == null) || ("".equals(callback.trim())))
            renderJson(response, text, codeing);
        else
            renderJson(response, callback + "(" + text + ");", codeing);
    }

    public static void renderText(HttpServletResponse response, String text, String codeing) {
        render(response, "text/plain", text, codeing);
    }

    public static void renderText(HttpServletResponse response, String text,
                                  String callback, String codeing) {
        if ((callback == null) || ("".equals(callback.trim())))
            renderText(response, text, codeing);
        else
            renderText(response, callback + "(\"" + text + "\");", codeing);
    }

    public static void renderXml(HttpServletResponse response, String text, String codeing) {
        render(response, "text/xml", text, codeing);
    }

    public static void renderHtml(HttpServletResponse response, String text, String codeing) {
        render(response, "text/html", text, codeing);
    }

    public static void renderJavaScript(HttpServletResponse response,
                                        String text, String codeing) {
        render(response, "text/javascript", text, codeing);
    }

    public static void renderXJavaScript(HttpServletResponse response,
                                         String text, String codeing) {
        render(response, "application/x-javascriptt", text, codeing);
    }

    public static void render(HttpServletResponse response, String contentType,
                              String text, String codeing) {
        if (StringUtils.isEmpty(codeing)) {
            codeing = "UTF-8";
        }
        response.setContentType(contentType + ";charset=" + codeing);
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0L);
        try {
            response.getWriter().write(text);
        } catch (IOException localIOException) {
        }
    }
}

